import { useEffect, useMemo, useRef } from 'react'
import Message from './Message'
import { currentChatAtom } from '../../atoms'
import { useAtomValue } from 'jotai'
import EditMessageDialog from '../Dialogs/EditMessage'

export default function MessageList() {
  const currentChat = useAtomValue(currentChatAtom)
  const messages = currentChat ? currentChat.messages : []
  const containRef = useRef<HTMLDivElement | null>(null)
  const mannalSroll = useRef(false)
  const wheelHandle = () => {
    mannalSroll.current = true
  }

  useMemo(() => {
    mannalSroll.current = false
  }, [messages.length])

  useEffect(() => {
    if (containRef.current && !mannalSroll.current) {
      containRef.current.scrollTo({
        top: containRef.current.scrollHeight,
        behavior: 'auto',
      })
    }
  }, [messages])

  return (
    <div className="w-full flex-1 overflow-y-auto pl-0 pr-0" ref={containRef} onWheel={wheelHandle}>
      <div className="m-auto w-55vw">
        {
          messages.map(msg => (
            <Message
              key={msg.id}
              msg={msg}
            />
          ))
        }
      </div>
      <EditMessageDialog />
    </div>
  )
}
